/*
** asm.c for asm in /home/boulah_m/corewar
**
** Made by moustafa boulahia
** Login   <boulah_m@epitech.net>
**
** Started on  Tue Feb  7 14:34:36 2012 moustafa boulahia
** Last update Thu Feb 16 12:49:18 2012 moustafa boulahia
*/

#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include "my.h"
#include "op.h"

void	header(char *name, int	fd, int fda)
{
  header_t head;

  head. magic = 0xea83f3;
  head.prog_size = size_file(fda);
  head.comment = "ceci est le header";
  head.prog_name = name;
  write(fd, "**\n", 3);
  my_putnbr_base_fd(head.magic, "0123456789abcdef", fd);
  write(fd, "\n", 1);
  write(fd, head.prog_name, my_strlen(head.prog_name));
  write(fd, "\n", 1);
  my_putnbr_base_fd(head.prog_size, "0123456789", fd);
  write(fd, "\n", 1);
  write(fd, head.comment, my_strlen(head.comment));
  write(fd, "\n**\n", 4);

}

int	cop(char *to_parse)
{
  int	fda;
  int	fdb;
  char	*new;
  char	*s;

  fda = open(to_parse,O_RDONLY);
  if (fda == -1)
    return (EXIT_FAILURE);
  new = malloc(my_strlen(to_parse) + 3);
  if (new != NULL)
    { new = my_strncpy(new, to_parse, my_strlen(to_parse) - 2);
      new = my_strcat(new, ".cor");
      fdb = open(new, O_RDWR | O_CREAT, S_IRWXU);
       if (fdb == -1)
	return (EXIT_FAILURE);
       header(new, fdb, fda);
       while ((s = get_line(fda)) != '\0')
	 write(fdb, s, my_strlen(s));
    }
  return (0);
}

int	main(int ac, char **av)
{
  int	i;

  if (ac < 2)
    my_printf("Use asm \"fichier.s\" \n");
  else
    {
      i = 1;
      while ( i < ac)
	{
	  cop(av[i]);
	  i++;
	}
    }
  return (0);
}
